<template>
  <div :data-title="title" v-title>
    <el-container>
      <blog-write-header
        :showCancelDialog="showCancelDialog"
        :showPublishDialog="showPublishDialog"
      />
      <el-container class="my-write-box">
        <el-main class="blog-write-main">
          <div class="blog-title">
            <el-input
              autosize
              class="my-write-input"
              placeholder="请输入标题"
              resize="none"
              type="textarea"
              v-model="articleForm.artName"
            ></el-input>
          </div>
          <div id="placeholder" style="visibility: hidden;height: 89px;display: none;"></div>
          <markdown-editor :editor="articleForm.editor" class="my-write-editor"></markdown-editor>
        </el-main>
      </el-container>
      <Footer />
    </el-container>

    <el-dialog :visible.sync="dialogVisible" title="摘要 分类 标签" width="50%">
      <el-form :model="articleForm" :rules="rules" ref="articleForm">
        <el-form-item prop="summary">
          <el-input
            class="article-summary"
            placeholder="请输入文章摘要"
            rows="5"
            type="textarea"
            v-model="articleForm.summary"
          ></el-input>
        </el-form-item>
        <el-form-item label="文章分类：" prop="tags">
          <el-select placeholder="请选择" v-model="articleForm.category">
            <el-option :key="c.id" :label="c.categoryName" :value="c.id" v-for="c in categories"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章标签:" prop="tags">
          <el-checkbox-group id="tag-check-box" v-model="articleForm.tags">
            <el-checkbox
              :key="t.id"
              :label="t.id"
              class="tag-check-box"
              name="tags"
              v-for="t in tags"
            >{{t.tagName}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <span class="dialog-footer" slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button @click="publish('articleForm')" type="primary">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import BlogWriteHeader from './BlogWriteHeader'
import markdownEditor from '@/components/markdown/markdownEditor'
import Footer from '@/layouts/Footer'
import { viewArticle, publishArticle } from '@/api/article'
import { getAllCategories } from '@/api/category'
import { getAllTags } from '@/api/tag'
export default {
  components: {
    'blog-write-header': BlogWriteHeader,
    'markdown-editor': markdownEditor,
    Footer
  },
  data () {
    return {
      dialogVisible: false,
      categories: [],
      tags: [],
      articleForm: {
        id: '',
        category: '',
        summary: '',
        tags: [],
        artName: '',
        editor: {
          value: '',
          ref: '',
          default_open: 'edit',
          toolbars: {
            bold: true, // 粗体
            italic: true, // 斜体
            header: true, // 标题
            underline: true, // 下划线
            strikethrough: true, // 中划线
            mark: true, // 标记
            superscript: true, // 上角标
            subscript: true, // 下角标
            quote: true, // 引用
            ol: true, // 有序列表
            ul: true, // 无序列表
            imagelink: true, // 图片链接
            code: true, // code
            link: true, // 超链接
            fullscreen: true, // 全屏编辑
            readmodel: true, // 沉浸式阅读
            help: true, // 帮助
            undo: true, // 上一步
            redo: true, // 下一步
            trash: true, // 清空
            navigation: true, // 导航目录
            // subfield: true, // 单双栏模式
            preview: true // 预览
          }
        }
      },
      rules: {
        summary: [
          { required: true, message: '请输入摘要', trigger: 'blur' },
          { max: 80, message: '不能大于80个字符', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择文章分类', trigger: 'change' }
        ],
        tags: [
          {
            type: 'array',
            trigger: 'change'
          }
        ]
      }
    }
  },
  mounted () {
    if (this.$route.params.id) {
      this.getArticleById(this.$route.params.id)
    }
    this.getAllCategories()
    this.getAllTags()
    window.addEventListener('scroll', this.toolBarToFixed, false)
  },
  beforeDestroy () {
    window.removeEventListener('scroll', this.toolBarToFixed, false)
  },
  computed: {
    title () {
      if (this.articleForm.id && !isNaN(this.articleForm.id)) {
        return '编辑 - MBlog'
      } else {
        return '写文章 - MBlog'
      }
    }
  },
  methods: {
    getAllCategories () {
      getAllCategories().then(data => {
        this.categories = data.data
      })
    },
    getAllTags () {
      getAllTags().then(data => {
        this.tags = data.data
      })
    },
    getArticleById (id) {
      let that = this
      viewArticle(id)
        .then(data => {
          Object.assign(this.articleForm, data.data)
          this.articleForm.category = this.articleForm.category.categoryId
          this.articleForm.editor.value = data.data.content
          let tags = this.articleForm.tags.map(function (item) {
            return item.tagId
          })
          this.articleForm.tags = tags
        })
        .catch(error => {
          if (error !== 'error') {
            that.$message({
              type: 'error',
              message: '文章加载失败',
              showClose: true
            })
          }
        })
    },
    showPublishDialog () {
      if (!this.articleForm.artName) {
        this.$message({
          message: '标题不能为空哦',
          type: 'warning',
          showClose: true
        })
        return
      }

      if (this.articleForm.artName.length > 30) {
        this.$message({
          message: '标题不能大于30个字符',
          type: 'warning',
          showClose: true
        })
        return
      }

      if (!this.articleForm.editor.ref.d_render) {
        this.$message({
          message: '内容不能为空哦',
          type: 'warning',
          showClose: true
        })
        return
      }
      this.dialogVisible = true
    },
    publish (articleForm) {
      let that = this
      this.$refs[articleForm].validate(valid => {
        if (valid) {
          let tags = []
          console.log(this.tags)
          if (this.articleForm.tags.length !== 0) {
            tags = this.articleForm.tags.map(function (id) {
              return { id }
            })
          }
          console.log(tags)
          let article = {
            id: this.articleForm.id,
            artName: this.articleForm.artName,
            summary: this.articleForm.summary,
            category: this.articleForm.category,
            nickname: this.$store.state.name,
            tags: tags,
            body: {
              content: this.articleForm.editor.value,
              contentHtml: this.articleForm.editor.ref.d_render
            }
          }
          this.publishVisible = false

          let loading = this.$loading({
            lock: true,
            text: '发布中，请稍后...'
          })
          let data = { nickname: this.$store.state.nickname, article: article }
          publishArticle(data)
            .then(data => {
              let id = data.data.articleId
              loading.close()
              that.$message({
                message: '发布成功啦',
                type: 'success',
                showClose: true
              })
              that.$router.push({ name: 'articleById', params: { id } })
            })
            .catch(error => {
              loading.close()
              if (error !== 'error') {
                that.$message({
                  message: error,
                  type: 'error',
                  showClose: true
                })
              }
            })
        } else {
          return false
        }
      })
    },
    showCancelDialog () {
      this.$confirm('文章将不会保存, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$router.push({ name: 'home' })
      })
    },
    toolBarToFixed () {
      let toolbar = document.querySelector('.v-note-op')
      let curHeight =
        document.documentElement.scrollTop || document.body.scrollTop
      if (curHeight >= 120) {
        toolbar.classList.add('my-write-toolbar-fixed')
      } else {
        toolbar.classList.remove('my-write-toolbar-fixed')
      }
    }
  }
}
</script>

<style>
.my-write-box {
  margin: 70px auto 0;
  margin-bottom: 30px;
  background-color: #f5f5f5;
  max-width: 60%;
}
.blog-title {
  line-height: 20px;
  max-width: 100%;
  border-bottom: 1px solid #f5f5f5;
}
.my-write-input textarea {
  font-size: 30px;
  font-weight: 500;
  border: none;
  height: 20px;
}
.my-write-editor {
  min-height: 650px !important;
}
.my-write-toolbar-fixed {
  position: fixed;
  width: 870px !important;
  top: 60px;
}
.article-tags li {
  list-style-type: none;
  display: inline-block;
  padding: 4px;
}
.article-summary,
.article-category,
.article-tags {
  padding: 5px;
}
.choose-tags {
  display: inline-block;
}
.tag-check-box {
  line-height: 40px;
}
</style>
